package me.jiatao.wan.ui.main.system

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import com.hi.dhl.binding.viewbind
import me.jiatao.wan.R
import me.jiatao.wan.databinding.FragmentSystemBinding

class SystemFragment : Fragment(R.layout.fragment_system) {

    private val mBinding: FragmentSystemBinding by viewbind()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.apply {
            /** 配置 */
            viewPager2.adapter = object : FragmentStateAdapter(this@SystemFragment) {
                override fun getItemCount(): Int {
                    return 2
                }

                override fun createFragment(position: Int): Fragment {
                    return if (position == 0) {
                        CategoryTreeFragment()
                    } else {
                        NavTreeFragment()
                    }
                }

            }
            TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
                when (position) {
                    0 -> tab.text = "体系"
                    1 -> tab.text = "导航"
                }
            }.attach()

            /** 关闭预加载,点击当前tab，创建fragment */
            viewPager2.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT

            /** 缓存所有加载项，避免销毁二次加载数据 */
            (viewPager2.getChildAt(0) as RecyclerView).setItemViewCacheSize(2)
        }
    }
}